package com.allen.app.helper

import android.graphics.Rect
import android.os.Handler
import android.os.Message
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.allen.base.utils.LogUtils
import com.allen.base.utils.NetWorkUtils
import com.allen.base.utils.SpUtils
import java.lang.ref.WeakReference

/**
 *   列表视频自动播放检测
 *   视频列表滚动停止会自动播放界面上可见区域第一个视频，这些逻辑设置RecycleView
 *   滑动监听（addOnScrollListener->onScrollStateChanged）后托管给AutoPlayVideoHandler。AutoPlayVideoHandler
 *   会判断列表是否滚动停止，滚动停止后会判断当前是否处于wifi状态或非wifi可播放标志->可见区域是否有完整显示的视频。
 * */
class AutoPlayVideoHandler(lm: LinearLayoutManager?, private var headLayoutCount: Int = 0, private var listener: AutoPlayVideoHandlerListener) : Handler() {

    companion object {
        const val MSG_HANDLER_PLAY_NEXT_VIDEO = 0//播放下一个视频

        //是否wifi情况下
        fun isWifiPlay(): Boolean {
            val isWifiPlay = SpUtils.getBoolean("isWifiPlay", true)
            if (!isWifiPlay || !NetWorkUtils.isWifiConnected())
                return false
            return true
        }

        //当 View 有一点点不可见时立即返回false!
        private fun isVisibleLocal(target: View?): Boolean {
            val rect = Rect()
            target?.getLocalVisibleRect(rect)
            return rect.top == 0
        }

        //是否在界面可见item之内
        private fun onScrollStopPlayVideo(layoutManager: LinearLayoutManager?, position: Int): Boolean {
            if (null == layoutManager)
                return false

            val firstItemPosition = layoutManager.findFirstVisibleItemPosition()
            val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()

            //是否在界面可见item之内
            if (position < firstItemPosition || position > lastVisibleItemPosition) {
                return true
            }
            return false
        }
    }

    private val layoutManagerWF: WeakReference<LinearLayoutManager?> = WeakReference(lm)

    override fun handleMessage(msg: Message?) {

        val layoutManager = layoutManagerWF.get() ?: return

        when (msg?.what) {
            MSG_HANDLER_PLAY_NEXT_VIDEO -> {

                if(!listener.onAutoPlayVideoHandlerViewVisible())
                    return

                val isWifiPlay = SpUtils.getBoolean("isWifiPlay", true)
                if (!isWifiPlay || !NetWorkUtils.isWifiConnected())
                    return

                val firstItemPosition = layoutManager.findFirstCompletelyVisibleItemPosition()
                val lastVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition()

                // i对应于界面，包含头部，，数据不包含头部
                for (i in firstItemPosition..lastVisibleItemPosition) {
                    val view = layoutManager.findViewByPosition(i)

                    //获取视频数据url
                    val url = listener.onAutoPlayVideoHandlerGetMediaPath(i - headLayoutCount)
                    if (url.isNullOrEmpty())
                        continue

                    //是否第一条完全可见
                    val visibleLocal = isVisibleLocal(listener.onAutoPlayVideoHandlerGetLayout(view))
                    if (!visibleLocal)
                        continue
                    listener.onAutoPlayVideoHandlerAdapterPlay(i - headLayoutCount,  view)
                    return
                }
            }
        }
    }

    //滚动状态更新
    fun onScrollStateChanged(newState: Int) {
        if (newState == 0) {
            //发送自动播放消息
            sendAutoPlayMessage()
        } else {
            //发送移除自动播放消息
            removeAutoPlayMessages()
        }
    }


    //发送自动播放消息
    fun sendAutoPlayMessage() {
        sendEmptyMessageDelayed(MSG_HANDLER_PLAY_NEXT_VIDEO, 500)
    }

    //发送移除自动播放消息
    fun removeAutoPlayMessages() {
        removeMessages(MSG_HANDLER_PLAY_NEXT_VIDEO)
    }


    interface AutoPlayVideoHandlerListener {
        fun onAutoPlayVideoHandlerViewVisible(): Boolean = true
        fun onAutoPlayVideoHandlerGetLayout(view: View?): View? = null
        fun onAutoPlayVideoHandlerGetMediaPath(index: Int): String?
        fun onAutoPlayVideoHandlerAdapterPlay(index: Int,  itemView: View?)
    }
}